package com.song.seckill.service;

import com.song.seckill.dao.SeckillMapper;
import com.song.seckill.dao.SeckillOrderMapper;
import com.song.seckill.model.SeckillOrder;
import com.song.seckill.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Service
public class SeckillService {

    @Autowired
    private JedisPool jedisPool;
    @Autowired
    SeckillMapper seckillMapper;
    @Autowired
    SeckillOrderMapper seckillOrderMapper;

    @PostConstruct
    public void initStock() {
        Jedis jedis = RedisUtil.getJedis();
        jedis.set("sku:1001_stock", "9900"); // 初始化库存
        jedis.close();
    }

    // Lua脚本原子扣减库存[1,5](@ref)
    private static final String STOCK_DECREASE_SCRIPT =
            "local stock = tonumber(redis.call('get', KEYS[1]))\n" +
                    "if stock and stock > 0 then\n" +
                    "    redis.call('decr', KEYS[1])\n" +
                    "    return 1\n" +
                    "else\n" +
                    "    return 0\n" +
                    "end";

    public boolean trySeckill(String skuId, String userId) {
        try (Jedis jedis = jedisPool.getResource()) {
            // 修正参数顺序：script, keyCount, keys, args
            Long result = (Long) jedis.eval(
                    STOCK_DECREASE_SCRIPT,
                    1,
                    "sku:" + skuId + "_stock"
            );
            return result != null && result == 1;
        }
    }

    public boolean checkRepeat(String userId, String skuId) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.sadd("seckill:users:" + skuId, userId) == 1;
        }
    }

    @Async("seckillExecutor")
    public boolean asyncUpdateStock(String skuId) {
        // 从Redis获取剩余库存
        Jedis jedis = jedisPool.getResource();
        int stockCount = Integer.parseInt(jedis.get("sku:" + skuId + "_stock"));
        // 批量更新MySQL[18,20](@ref)
        int resultNum = seckillMapper.updateStock(skuId, stockCount);
        return resultNum>0;
    }

    public boolean createOrder(String skuId, String userId){
        SeckillOrder seckillOrder = new SeckillOrder();

        return seckillOrderMapper.insert(seckillOrder)>0;

    }
}
